package com.windy.myvideo.player;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.windy.myvideo.R;
import com.windy.myvideo.utils.LayoutQuery;
import com.windy.myvideo.widget.IRenderView;
import com.windy.myvideo.widget.IjkVideoView;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

/**
 * Created by tcking on 15/10/27.
 */
public class WindyPlayer {

    private final static String TAG = WindyPlayer.class.getSimpleName();

    /**
     * fitParent:scale the video uniformly (maintain the video's aspect ratio) so that both dimensions (width and height) of the video will be equal to or **less** than the corresponding dimension of the view. like ImageView's `CENTER_INSIDE`.等比缩放,画面填满view。
     */
    public static final String SCALETYPE_FITPARENT = "fitParent";
    /**
     * fillParent:scale the video uniformly (maintain the video's aspect ratio) so that both dimensions (width and height) of the video will be equal to or **larger** than the corresponding dimension of the view .like ImageView's `CENTER_CROP`.等比缩放,直到画面宽高都等于或小于view的宽高。
     */
    public static final String SCALETYPE_FILLPARENT = "fillParent";
    /**
     * wrapContent:center the video in the view,if the video is less than view perform no scaling,if video is larger than view then scale the video uniformly so that both dimensions (width and height) of the video will be equal to or **less** than the corresponding dimension of the view. 将视频的内容完整居中显示，如果视频大于view,则按比例缩视频直到完全显示在view中。
     */
    public static final String SCALETYPE_WRAPCONTENT = "wrapContent";
    /**
     * fitXY:scale in X and Y independently, so that video matches view exactly.不剪裁,非等比例拉伸画面填满整个View
     */
    public static final String SCALETYPE_FITXY = "fitXY";
    /**
     * 16:9:scale x and y with aspect ratio 16:9 until both dimensions (width and height) of the video will be equal to or **less** than the corresponding dimension of the view.不剪裁,非等比例拉伸画面到16:9,并完全显示在View中。
     */
    public static final String SCALETYPE_16_9 = "16:9";
    /**
     * 4:3:scale x and y with aspect ratio 4:3 until both dimensions (width and height) of the video will be equal to or **less** than the corresponding dimension of the view.不剪裁,非等比例拉伸画面到4:3,并完全显示在View中。
     */
    public static final String SCALETYPE_4_3 = "4:3";

    private int STATUS_ERROR = -1;
    private int STATUS_IDLE = 0;
    private int STATUS_LOADING = 1;
    private int STATUS_PLAYING = 2;
    private int STATUS_PAUSE = 3;
    private int STATUS_COMPLETED = 4;

    private final Activity mActivity;
    private final AudioManager mAudioManager;
    private final GestureDetector mGestureDetector;

    private final int mMaxVolume;
    private boolean playerSupport;
    private String url;
    private LayoutQuery $;

    private long pauseTime;
    private int status = STATUS_IDLE;
    private boolean isLive = false;//是否为直播
    private OrientationEventListener orientationEventListener;
    final private int initHeight;
    private int defaultTimeout = 3000;
    private int screenWidthPixels;

    private boolean isShowing;
    private boolean portrait;
    private float brightness = -1;
    private int volume = -1;
    private long newPosition = -1;
    private long defaultRetryTime = 5000;

    private int currentPosition;
    private boolean fullScreenOnly = false;

    private long duration;
    private boolean instantSeeking = false;
    private boolean isDragging;

    /***********************
     * 控件
     *********************************/
    private View videoBox;
    private IjkVideoView mVideoView;
    private SeekBar mSeekBar;
    private ImageView videoPlay;
    private ImageView videoFullScreen;
    private ImageView videoReplay;
    private ImageView backIcon;

    private View volumeBox;
    private View brightnessBox;
    private View fastForwardBox;

    private ImageView volumeIcon;
    private TextView volumePercent;

    private ImageView brightnessIcon;
    private TextView brightnessPercent;

    private TextView fastForwardTime;
    private TextView fastForwardTarget;
    private TextView fastForwardAll;

    private View bottomBox;
    private ProgressBar progressBar;
    private View videoStatus;
    private TextView videoStatusText;
    private TextView videoCurrentTime;
    private TextView videoEndTime;

    private View topBox;
    private TextView videoTitle;
    /********************************************************/

    private static final int MESSAGE_SHOW_PROGRESS = 1;
    private static final int MESSAGE_FADE_OUT = 2;
    private static final int MESSAGE_SEEK_NEW_POSITION = 3;
    private static final int MESSAGE_HIDE_CENTER_BOX = 4;
    private static final int MESSAGE_RESTART_PLAY = 5;

    @SuppressWarnings("HandlerLeak")
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_FADE_OUT:
                    hide(false);
                    break;
                case MESSAGE_HIDE_CENTER_BOX:
                    volumeBox.setVisibility(View.GONE);
                    brightnessBox.setVisibility(View.GONE);
                    fastForwardBox.setVisibility(View.GONE);
                    break;
                case MESSAGE_SEEK_NEW_POSITION:
                    if (!isLive && newPosition >= 0) {
                        mVideoView.seekTo((int) newPosition);
                        newPosition = -1;
                    }
                    break;
                case MESSAGE_SHOW_PROGRESS:
                    setProgress();
                    if (!isDragging && isShowing) {
                        msg = obtainMessage(MESSAGE_SHOW_PROGRESS);
                        sendMessageDelayed(msg, 1000);
                        updatePausePlay();
                    }
                    break;
                case MESSAGE_RESTART_PLAY:
                    play(url);
                    break;
            }
        }
    };

    public WindyPlayer(final Activity activity) {
        try {
            IjkMediaPlayer.loadLibrariesOnce(null);
            IjkMediaPlayer.native_profileBegin("libijkplayer.so");
            playerSupport = true;
        } catch (Throwable e) {
            Log.e(TAG, "loadLibraries error", e);
        }
        mActivity = activity;
        initView(activity);
        screenWidthPixels = activity.getResources().getDisplayMetrics().widthPixels;
        $ = new LayoutQuery(activity);

        mVideoView.setOnCompletionListener(onCompletionListener);
        mVideoView.setOnErrorListener(onErrorListener);
        mVideoView.setOnInfoListener(onInfoListener);

        mAudioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
        mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mGestureDetector = new GestureDetector(activity, new PlayerGestureListener());

        if (fullScreenOnly) {
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        portrait = getScreenOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        initHeight = videoBox.getLayoutParams().height;
        hideAll();
        if (!playerSupport) {
            showStatus(activity.getResources().getString(R.string.not_support));
        }

        orientationEventListener = new OrientationEventListener(activity) {
            @Override
            public void onOrientationChanged(int orientation) {
                if (orientation >= 0 && orientation <= 30 || orientation >= 330 || (orientation >= 150 && orientation <= 210)) {
                    //竖屏
                    if (portrait) {
                        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
                        orientationEventListener.disable();
                    }
                } else if ((orientation >= 90 && orientation <= 120) || (orientation >= 240 && orientation <= 300)) {
                    if (!portrait) {
                        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
                        orientationEventListener.disable();
                    }
                }
            }
        };

    }

    private void initView(final Activity activity) {
        videoBox = activity.findViewById(R.id.app_video_box);
        videoBox.setClickable(true);
        videoBox.setOnTouchListener(onTouchListener);

        mVideoView = (IjkVideoView) activity.findViewById(R.id.video_view);

        videoPlay = (ImageView) activity.findViewById(R.id.app_video_play);
        videoFullScreen = (ImageView) activity.findViewById(R.id.app_video_fullscreen);
        videoReplay = (ImageView) activity.findViewById(R.id.app_video_replay_icon);
        backIcon = (ImageView) activity.findViewById(R.id.app_video_finish);

        videoPlay.setOnClickListener(onClickListener);
        videoFullScreen.setOnClickListener(onClickListener);
        videoReplay.setOnClickListener(onClickListener);
        backIcon.setOnClickListener(onClickListener);

        volumeBox = activity.findViewById(R.id.app_video_volume_box);
        brightnessBox = activity.findViewById(R.id.app_video_brightness_box);
        fastForwardBox = activity.findViewById(R.id.app_video_fastForward_box);

        volumeIcon = (ImageView) activity.findViewById(R.id.app_video_volume_icon);
        volumePercent = (TextView) activity.findViewById(R.id.app_video_volume);
        brightnessIcon = (ImageView) activity.findViewById(R.id.app_video_brightness_icon);
        brightnessPercent = (TextView) activity.findViewById(R.id.app_video_brightness);

        fastForwardTime = (TextView) activity.findViewById(R.id.app_video_fastForward);
        fastForwardTarget = (TextView) activity.findViewById(R.id.app_video_fastForward_target);
        fastForwardAll = (TextView) activity.findViewById(R.id.app_video_fastForward_all);

        // seek bar
        mSeekBar = (SeekBar) activity.findViewById(R.id.app_video_seekBar);
        mSeekBar.setMax(1000);
        mSeekBar.setOnSeekBarChangeListener(mSeekListener);

        bottomBox = activity.findViewById(R.id.app_video_bottom_box);
        progressBar = (ProgressBar) activity.findViewById(R.id.app_video_loading);
        videoStatus = activity.findViewById(R.id.app_video_status);
        videoStatusText = (TextView) activity.findViewById(R.id.app_video_status_text);
        videoCurrentTime = (TextView) activity.findViewById(R.id.app_video_currentTime);
        videoEndTime = (TextView) activity.findViewById(R.id.app_video_endTime);

        topBox = activity.findViewById(R.id.app_video_top_box);
        videoTitle = (TextView) activity.findViewById(R.id.app_video_title);
    }

    IMediaPlayer.OnCompletionListener onCompletionListener = new IMediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(IMediaPlayer mp) {
            statusChange(STATUS_COMPLETED);
        }
    };

    IMediaPlayer.OnErrorListener onErrorListener = new IMediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(IMediaPlayer mp, int what, int extra) {
            statusChange(STATUS_ERROR);
            return true;
        }
    };

    IMediaPlayer.OnInfoListener onInfoListener = new IMediaPlayer.OnInfoListener() {
        @Override
        public boolean onInfo(IMediaPlayer mp, int what, int extra) {
            switch (what) {
                case IMediaPlayer.MEDIA_INFO_BUFFERING_START:
                    statusChange(STATUS_LOADING);
                    break;
                case IMediaPlayer.MEDIA_INFO_BUFFERING_END:
                    statusChange(STATUS_PLAYING);
                    break;
                case IMediaPlayer.MEDIA_INFO_NETWORK_BANDWIDTH:
                    //显示 下载速度
                    Log.d(TAG, "download rate:" + extra);
                    break;
                case IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                    statusChange(STATUS_PLAYING);
                    break;
            }
            return false;
        }
    };

    private final View.OnTouchListener onTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (mGestureDetector != null && mGestureDetector.onTouchEvent(event)) {
                return true;
            }
            // 处理手势结束
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_UP:
                    endGesture();
                    break;
            }
            return false;
        }
    };

    /**
     * 手势结束
     */
    private void endGesture() {
        volume = -1;
        brightness = -1f;
        if (newPosition >= 0) {
            mHandler.removeMessages(MESSAGE_SEEK_NEW_POSITION);
            mHandler.sendEmptyMessage(MESSAGE_SEEK_NEW_POSITION);
        }
        mHandler.removeMessages(MESSAGE_HIDE_CENTER_BOX);
        mHandler.sendEmptyMessageDelayed(MESSAGE_HIDE_CENTER_BOX, 500);
    }

    private final View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.app_video_fullscreen:
                    toggleFullScreen();
                    break;
                case R.id.app_video_play:
                    doPauseResume();
                    show(defaultTimeout);
                    break;
                case R.id.app_video_replay_icon:
                    if (!fullScreenOnly && !portrait) {
                        mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    } else {
                        mActivity.finish();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    // 进度条滑动监听
    private final SeekBar.OnSeekBarChangeListener mSeekListener = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            isDragging = true;
            show(3600000);
            mHandler.removeMessages(MESSAGE_SHOW_PROGRESS);
            if (instantSeeking) {
                mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
            }
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (!fromUser) {
                return;
            }
            videoStatus.setVisibility(View.GONE);//移动时隐藏掉状态image
            int newPosition = (int) ((duration * progress * 1.0) / 1000);
            String time = generateTime(newPosition);
            if (instantSeeking) {
                mVideoView.seekTo(newPosition);
            }
            videoCurrentTime.setText(time);
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            if (!instantSeeking) {
                mVideoView.seekTo((int) ((duration * seekBar.getProgress() * 1.0) / 1000));
            }
            show(defaultTimeout);
            mHandler.removeMessages(MESSAGE_SHOW_PROGRESS);
            mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
            isDragging = false;
            mHandler.sendEmptyMessageDelayed(MESSAGE_SHOW_PROGRESS, 1000);
        }
    };

    // 手势监听
    public class PlayerGestureListener extends GestureDetector.SimpleOnGestureListener {

        private boolean firstTouch;
        private boolean volumeControl;
        private boolean toSeek;

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            mVideoView.toggleAspectRatio();
            return true;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            firstTouch = true;
            return super.onDown(e);
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            float mOldX = e1.getX(), mOldY = e1.getY();
            float deltaY = mOldY - e2.getY();
            float deltaX = mOldX - e2.getX();
            if (firstTouch) {
                toSeek = Math.abs(distanceX) >= Math.abs(distanceY);
                volumeControl = mOldX > screenWidthPixels * 0.5f;
                firstTouch = false;
            }

            if (toSeek) {
                if (!isLive) {
                    onProgressSlide(-deltaX / mVideoView.getWidth());
                }
            } else {
                float percent = deltaY / mVideoView.getHeight();
                if (volumeControl) {
                    onVolumeSlide(percent);
                } else {
                    onBrightnessSlide(percent);
                }
            }
            return super.onScroll(e1, e2, distanceX, distanceY);
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            if (isShowing) {
                hide(false);
            } else {
                show(defaultTimeout);
            }
            return true;
        }
    }

    /**
     * 滑动改变声音大小
     *
     * @param percent
     */
    private void onVolumeSlide(float percent) {
        if (volume == -1) {
            volume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if (volume < 0) {
                volume = 0;
            }
        }
        hide(true);
        int index = (int) (percent * mMaxVolume) + volume;
        if (index > mMaxVolume) {
            index = mMaxVolume;
        } else if (index < 0) {
            index = 0;
        }
        // 变更声音
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);
        // 变更进度条
        int i = (int) (index * 1.0 / mMaxVolume * 100);
        String s = i + "%";
        if (i == 0) {
            s = "off";
        }
        // 显示
        brightnessBox.setVisibility(View.GONE);
        volumeBox.setVisibility(View.VISIBLE);
        volumeIcon.setImageResource(i == 0 ? R.drawable.ic_volume_off_white_36dp : R.drawable.ic_volume_up_white_36dp);
        volumePercent.setText(s);
    }

    /**
     * 滑动改变进度
     *
     * @param percent
     */
    private void onProgressSlide(float percent) {
        long position = mVideoView.getCurrentPosition();
        long duration = mVideoView.getDuration();
        long deltaMax = Math.min(100 * 1000, duration - position);
        long delta = (long) (deltaMax * percent);

        newPosition = delta + position;
        if (newPosition > duration) {
            newPosition = duration;
        } else if (newPosition <= 0) {
            newPosition = 0;
            delta = -position;
        }
        int showDelta = (int) delta / 1000;
        if (showDelta != 0) {
            fastForwardBox.setVisibility(View.VISIBLE);
            String text = showDelta > 0 ? ("+" + showDelta) : "" + showDelta;
            fastForwardTime.setText(text + "s");
            fastForwardTarget.setText(generateTime(newPosition) + "/");
            fastForwardAll.setText(generateTime(duration));
        }
    }

    /**
     * 滑动改变亮度
     *
     * @param percent
     */
    private void onBrightnessSlide(float percent) {
        if (brightness < 0) {
            brightness = mActivity.getWindow().getAttributes().screenBrightness;
            if (brightness <= 0.00f) {
                brightness = 0.50f;
            } else if (brightness < 0.01f) {
                brightness = 0.01f;
            }
        }
        Log.d(TAG, "brightness:" + brightness + ",percent:" + percent);
        brightnessBox.setVisibility(View.VISIBLE);
        WindowManager.LayoutParams lpa = mActivity.getWindow().getAttributes();
        lpa.screenBrightness = brightness + percent;
        if (lpa.screenBrightness > 1.0f) {
            lpa.screenBrightness = 1.0f;
        } else if (lpa.screenBrightness < 0.01f) {
            lpa.screenBrightness = 0.01f;
        }
        brightnessPercent.setText(((int) (lpa.screenBrightness * 100)) + "%");
        mActivity.getWindow().setAttributes(lpa);
    }

    /**
     * try to play when error(only for live video)
     *
     * @param defaultRetryTime millisecond,0 will stop retry,default is 5000 millisecond
     */
    public void setDefaultRetryTime(long defaultRetryTime) {
        this.defaultRetryTime = defaultRetryTime;
    }

    // set video title
    public void setTitle(CharSequence title) {
        videoTitle.setText(title);
    }

    private void doPauseResume() {
        if (status == STATUS_COMPLETED) {
            videoReplay.setVisibility(View.GONE);
            mVideoView.seekTo(0);
            mVideoView.start();
        } else if (mVideoView.isPlaying()) {
            statusChange(STATUS_PAUSE);
            mVideoView.pause();
        } else {
            mVideoView.start();
        }
        updatePausePlay();
    }

    private void updatePausePlay() {
        if (mVideoView.isPlaying()) {
            videoPlay.setImageResource(R.drawable.ic_stop_white_24dp);
        } else {
            videoPlay.setImageResource(R.drawable.ic_play_arrow_white_24dp);
        }
    }

    /**
     * @param timeout
     */
    public void show(int timeout) {
        if (!isShowing) {
            topBox.setVisibility(View.VISIBLE);
            if (!isLive) {
                showBottomControl(true);
            }
            if (!fullScreenOnly) {
                videoFullScreen.setVisibility(View.VISIBLE);
            }
            isShowing = true;
        }
        updatePausePlay();
        mHandler.sendEmptyMessage(MESSAGE_SHOW_PROGRESS);
        mHandler.removeMessages(MESSAGE_FADE_OUT);
        if (timeout != 0) {
            mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_FADE_OUT), timeout);
        }
    }

    /**
     * 显示/隐藏底部控制栏
     *
     * @param show
     */
    private void showBottomControl(boolean show) {
        bottomBox.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    /**
     * 隐藏所有控件
     */
    private void hideAll() {
        videoReplay.setVisibility(View.GONE);
        topBox.setVisibility(View.GONE);
        progressBar.setVisibility(View.GONE);
        videoFullScreen.setVisibility(View.INVISIBLE);
        videoStatus.setVisibility(View.GONE);

        showBottomControl(false);
    }

    private void statusChange(int newStatus) {
        status = newStatus;
        if (!isLive && newStatus == STATUS_COMPLETED) {
            mHandler.removeMessages(MESSAGE_SHOW_PROGRESS);
            hideAll();
            videoReplay.setVisibility(View.VISIBLE);
        } else if (newStatus == STATUS_ERROR) {
            mHandler.removeMessages(MESSAGE_SHOW_PROGRESS);
            hideAll();
            if (isLive) {
                showStatus(mActivity.getResources().getString(R.string.small_problem));
                if (defaultRetryTime > 0) {
                    mHandler.sendEmptyMessageDelayed(MESSAGE_RESTART_PLAY, defaultRetryTime);
                }
            } else {
                showStatus(mActivity.getResources().getString(R.string.small_problem));
            }
        } else if (newStatus == STATUS_LOADING) {
            hideAll();
            progressBar.setVisibility(View.VISIBLE);
        } else if (newStatus == STATUS_PLAYING) {
            hideAll();
        }
    }

    public void onResume() {
        pauseTime = 0;
        if (status == STATUS_PLAYING) {
            if (isLive) {
                mVideoView.seekTo(0);
            } else {
                if (currentPosition > 0) {
                    mVideoView.seekTo(currentPosition);
                }
            }
            mVideoView.start();
        }
    }

    public void onPause() {
        pauseTime = System.currentTimeMillis();
        show(0);//把系统状态栏显示出来
        if (status == STATUS_PLAYING) {
            mVideoView.pause();
            if (!isLive) {
                currentPosition = mVideoView.getCurrentPosition();
            }
        }
    }

    public void onDestroy() {
        orientationEventListener.disable();
        mHandler.removeCallbacksAndMessages(null);
        mVideoView.stopPlayback();
    }

    public void onConfigurationChanged(final Configuration newConfig) {
        portrait = newConfig.orientation == Configuration.ORIENTATION_PORTRAIT;
        doOnConfigurationChanged(portrait);
    }

    private void doOnConfigurationChanged(final boolean portrait) {
        if (mVideoView != null && !fullScreenOnly) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    tryFullScreen(!portrait);
                    if (portrait) {
                        $.id(R.id.app_video_box).height(initHeight, false);
                    } else {
                        int heightPixels = mActivity.getResources().getDisplayMetrics().heightPixels;
                        int widthPixels = mActivity.getResources().getDisplayMetrics().widthPixels;
                        $.id(R.id.app_video_box).height(Math.min(heightPixels, widthPixels), false);
                    }
                    updateFullScreenButton();
                }
            });
            orientationEventListener.enable();
        }
    }

    private void tryFullScreen(boolean fullScreen) {
        if (mActivity instanceof AppCompatActivity) {
            ActionBar supportActionBar = ((AppCompatActivity) mActivity).getSupportActionBar();
            if (supportActionBar != null) {
                if (fullScreen) {
                    supportActionBar.hide();
                } else {
                    supportActionBar.show();
                }
            }
        }
        setFullScreen(fullScreen);
    }

    private void setFullScreen(boolean fullScreen) {
        if (mActivity != null) {
            WindowManager.LayoutParams attrs = mActivity.getWindow().getAttributes();
            if (fullScreen) {
                attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
                mActivity.getWindow().setAttributes(attrs);
                mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            } else {
                attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
                mActivity.getWindow().setAttributes(attrs);
                mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            }
        }
    }

    private void showStatus(String statusText) {
        videoStatus.setVisibility(View.VISIBLE);
        videoStatusText.setText(statusText);
    }

    private String generateTime(long time) {
        int totalSeconds = (int) (time / 1000);
        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;
        return hours > 0 ? String.format("%02d:%02d:%02d", hours, minutes, seconds) : String.format("%02d:%02d", minutes, seconds);
    }

    private int getScreenOrientation() {
        int rotation = mActivity.getWindowManager().getDefaultDisplay().getRotation();
        DisplayMetrics dm = new DisplayMetrics();
        mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        int height = dm.heightPixels;
        int orientation;
        // if the device's natural orientation is portrait:
        if ((rotation == Surface.ROTATION_0
                || rotation == Surface.ROTATION_180) && height > width ||
                (rotation == Surface.ROTATION_90
                        || rotation == Surface.ROTATION_270) && width > height) {
            switch (rotation) {
                case Surface.ROTATION_0:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                    break;
                case Surface.ROTATION_90:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                    break;
                case Surface.ROTATION_180:
                    orientation =
                            ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
                    break;
                case Surface.ROTATION_270:
                    orientation =
                            ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
                    break;
                default:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                    break;
            }
        }
        // if the device's natural orientation is landscape or if the device
        // is square:
        else {
            switch (rotation) {
                case Surface.ROTATION_0:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                    break;
                case Surface.ROTATION_90:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                    break;
                case Surface.ROTATION_180:
                    orientation =
                            ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
                    break;
                case Surface.ROTATION_270:
                    orientation =
                            ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
                    break;
                default:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                    break;
            }
        }

        return orientation;
    }

    /**
     * set seek bar progress
     *
     * @return
     */
    private long setProgress() {
        if (isDragging) {
            return 0;
        }
        long position = mVideoView.getCurrentPosition();
        long duration = mVideoView.getDuration();
        if (mSeekBar != null) {
            if (duration > 0) {
                long pos = 1000L * position / duration;
                mSeekBar.setProgress((int) pos);
            }
            int percent = mVideoView.getBufferPercentage();
            mSeekBar.setSecondaryProgress(percent * 10);
        }

        this.duration = duration;
        $.id(R.id.app_video_currentTime).text(generateTime(position));
        $.id(R.id.app_video_endTime).text(generateTime(this.duration));
        return position;
    }

    public void hide(boolean force) {
        if (force || isShowing) {
            mHandler.removeMessages(MESSAGE_SHOW_PROGRESS);
            showBottomControl(false);
            topBox.setVisibility(View.GONE);
            videoFullScreen.setVisibility(View.INVISIBLE);
            isShowing = false;
        }
    }

    /**
     * using constants in GiraffePlayer,eg: GiraffePlayer.SCALETYPE_FITPARENT
     *
     * @param scaleType
     */
    public void setScaleType(String scaleType) {
        if (SCALETYPE_FITPARENT.equals(scaleType)) {
            mVideoView.setAspectRatio(IRenderView.AR_ASPECT_FIT_PARENT);
        } else if (SCALETYPE_FILLPARENT.equals(scaleType)) {
            mVideoView.setAspectRatio(IRenderView.AR_ASPECT_FILL_PARENT);
        } else if (SCALETYPE_WRAPCONTENT.equals(scaleType)) {
            mVideoView.setAspectRatio(IRenderView.AR_ASPECT_WRAP_CONTENT);
        } else if (SCALETYPE_FITXY.equals(scaleType)) {
            mVideoView.setAspectRatio(IRenderView.AR_MATCH_PARENT);
        } else if (SCALETYPE_16_9.equals(scaleType)) {
            mVideoView.setAspectRatio(IRenderView.AR_16_9_FIT_PARENT);
        } else if (SCALETYPE_4_3.equals(scaleType)) {
            mVideoView.setAspectRatio(IRenderView.AR_4_3_FIT_PARENT);
        }
    }

    /**
     * 是否显示左上返回图标(一般有actionbar or appToolbar时需要隐藏)
     *
     * @param show
     */
    public void setShowBackIcon(boolean show) {
//        $.id(R.id.app_video_finish).visibility(show ? View.VISIBLE : View.GONE);
        backIcon.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    /**
     * 播放
     *
     * @param url
     */
    public void play(String url) {
        this.url = url;
        if (playerSupport) {
//            $.id(R.id.app_video_loading).visible();
            progressBar.setVisibility(View.VISIBLE);
            mVideoView.setVideoPath(url);
            start();
        }
    }

    /**
     * 开始播放
     */
    public void start() {
        mVideoView.start();
    }

    /**
     * 暂停播放
     */
    public void pause() {
        mVideoView.pause();
    }

    /**
     * 是否正在播放
     *
     * @return
     */
    public boolean isPlaying() {
        return mVideoView != null ? mVideoView.isPlaying() : false;
    }

    /**
     * 停止播放
     */
    public void stop() {
        mVideoView.stopPlayback();
    }

    /**
     * seekTo position
     *
     * @param msec millisecond
     */
    public void seekTo(int msec, boolean showControlPanle) {
        mVideoView.seekTo(msec);
        if (showControlPanle) {
            show(defaultTimeout);
        }
    }

    /**
     * get video duration
     *
     * @return
     */
    public int getDuration() {
        return mVideoView.getDuration();
    }

    /**
     * 向前滑动
     *
     * @param percent
     */
    public void forward(float percent) {
        if (isLive || percent > 1 || percent < -1) {
            return;
        }
        onProgressSlide(percent);
        showBottomControl(true);
        mHandler.sendEmptyMessage(MESSAGE_SHOW_PROGRESS);
        endGesture();
    }

    /**
     * 当前播放进度
     *
     * @return
     */
    public int getCurrentPosition() {
        return mVideoView.getCurrentPosition();
    }

    /**
     * is player support this device
     *
     * @return
     */
    public boolean isPlayerSupport() {
        return playerSupport;
    }

    private void updateFullScreenButton() {
        if (getScreenOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            videoFullScreen.setImageResource(R.drawable.ic_fullscreen_exit_white_36dp);
        } else {
            videoFullScreen.setImageResource(R.drawable.ic_fullscreen_white_24dp);
        }
    }

    public void setFullScreenOnly(boolean fullScreenOnly) {
        this.fullScreenOnly = fullScreenOnly;
        tryFullScreen(fullScreenOnly);
        if (fullScreenOnly) {
            mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        }
    }

    public void playInFullScreen(boolean fullScreen) {
        if (fullScreen) {
            mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            updateFullScreenButton();
        }
    }

    public void toggleFullScreen() {
        if (getScreenOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        updateFullScreenButton();
    }

    /**
     * 切换宽高比
     */
    public void toggleAspectRatio() {
        if (mVideoView != null) {
            mVideoView.toggleAspectRatio();
        }
    }

    /**
     * set is live (can't seek forward)
     *
     * @param isLive
     * @return
     */
    public void live(boolean isLive) {
        this.isLive = isLive;
    }

    public boolean onBackPressed() {
        if (!fullScreenOnly && getScreenOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            return true;
        }
        return false;
    }


}
